package com.example.coffeeseller_2.widget;

import android.animation.Animator;
import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PointF;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSmoothScroller;
import android.support.v7.widget.RecyclerView;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;

import com.example.coffeeseller_2.R;
import com.example.coffeeseller_2.model.beans.ChooseCoffeeInfo;
import com.example.coffeeseller_2.model.beans.Coffee;
import com.example.coffeeseller_2.model.beans.PointAttr;
import com.example.coffeeseller_2.model.factory.BuyState;
import com.example.coffeeseller_2.model.helper.MyPagerSnapHelper;
import com.example.coffeeseller_2.model.helper.TradeAnimManager;
import com.example.coffeeseller_2.model.helper.view_helper.CreateCoffeeLayoutHelper;
import com.example.coffeeseller_2.model.helper.view_helper.CreatePointHelper;
import com.example.coffeeseller_2.model.listenner.OnCoffeeChildClickListenner;
import com.example.coffeeseller_2.model.listenner.OnRecycleTouchListenner;
import com.example.coffeeseller_2.utils.MyLog;
import com.example.coffeeseller_2.utils.ObjectAnimatorUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class RecyclerViewBanner extends FrameLayout {

    private static String TAG = "RecyclerViewBanner";
    private int defaultInterval = 15 * 1000;
    private int mInterval;
    private int pointSize, pointMaxSize;
    private int pointSelectedColor;
    private int pointUnSelectedColor;
    private int pointMargin, pointLayoutMarginTop;
    private float touchWaitTime;

    private Context context;
    private RecyclerView mRecyclerView;
    private CreatePointHelper createPointHelper;
    private PointAttr pointAttr;
    private RecyclerAdapter adapter;
    private List<Coffee> mData = new ArrayList<>();
    private int startX, startY, currentIndex;
    private boolean isPlaying;
    private Handler handler = new Handler();
    private CreateCoffeeLayoutHelper createCoffeeLayoutHelper;
    private OnCoffeeChildClickListenner onChildClickListenner;
    private boolean isTouched;
    private boolean isAutoPlaying = true;
    private boolean isCheckTime = false;
    private boolean isVisiable = true;//是否可见
    private long lastTouchTime;
    private long lastClickTime;
    private int pageCount;
    private int curPosition = 0;
    private OnRecycleTouchListenner onTouchListenner;
    private Timer timer;
    private TimerTask timerTask;
    private Runnable playTask = new Runnable() {

        @Override
        public void run() {
            if (!isVisiable) {
                return;
            }
            if (isAutoPlaying && !isTouched) {

                mRecyclerView.smoothScrollToPosition(++currentIndex);
                createPointHelper.changeSelectedPoint(currentIndex);
                handler.postDelayed(this, mInterval);
            }
        }
    };

    public RecyclerViewBanner(Context context) {
        this(context, null);
    }

    public RecyclerViewBanner(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public RecyclerViewBanner(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {

        mInterval = defaultInterval;
        this.context = context;
        getAttr(context, attrs);
        createCoffeeLayoutHelper = new CreateCoffeeLayoutHelper();
        createPointHelper = new CreatePointHelper(context);
        initRecycleView(context);
        addView(createPointHelper.getPointLayout());
    }

    private void initRecycleView(Context context) {
        mRecyclerView = new RecyclerView(context);
        // new MyPagerSnapHelper().attachToRecyclerView(mRecyclerView);
//        PagerSnapHelper snapHelper = new PagerSnapHelper();


        //new LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
        FastScrollLinearLayoutManager layoutManager = new FastScrollLinearLayoutManager(context
                , LinearLayoutManager.HORIZONTAL, false);
        mRecyclerView.setLayoutManager(layoutManager);
        MyPagerSnapHelper snapHelper = new MyPagerSnapHelper(mRecyclerView, layoutManager);
        snapHelper.attachToRecyclerView(mRecyclerView);
        adapter = new RecyclerAdapter();
        mRecyclerView.setAdapter(adapter);
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {
                    int first = ((LinearLayoutManager) recyclerView.getLayoutManager()).findFirstVisibleItemPosition();//第一个可见视图
                    int last = ((LinearLayoutManager) recyclerView.getLayoutManager()).findLastVisibleItemPosition();//第二个可见视图
                    if (first == last && currentIndex != last) {
                        currentIndex = last;
                        if (isTouched) {
                            createPointHelper.changeSelectedPoint(currentIndex);
                        }
                    }

                    if (onTouchListenner != null) {
                        onTouchListenner.onTouched(false);
                    }
                }


            }
        });
        LayoutParams vpLayoutParams = new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        vpLayoutParams.gravity = Gravity.CENTER;
        vpLayoutParams.bottomMargin = pointLayoutMarginTop;
        addView(mRecyclerView, vpLayoutParams);
    }

    private void getAttr(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.RecyclerViewBanner);
        try {
            mInterval = typedArray.getInt(R.styleable.RecyclerViewBanner_interval, defaultInterval);
            pointSelectedColor = typedArray.getColor(R.styleable.RecyclerViewBanner_pointSelectedColor, ContextCompat.getColor(context, R.color.white));
            pointUnSelectedColor = typedArray.getColor(R.styleable.RecyclerViewBanner_pointUnSelectedColor, ContextCompat.getColor(context, R.color.white));
            pointSize = (int) (typedArray.getDimension(R.styleable.RecyclerViewBanner_pointSize, 10) * 4 / 3);
            pointMaxSize = (int) (typedArray.getDimension(R.styleable.RecyclerViewBanner_pointMaxSize, 10) * 4 / 3);
            pointMargin = (int) (typedArray.getDimension(R.styleable.RecyclerViewBanner_pointSize, 10) * 4 / 3);
            pointLayoutMarginTop = (int) (typedArray.getDimension(R.styleable.RecyclerViewBanner_pointLayoutMarginTop, 10) * 4 / 3);
            touchWaitTime = typedArray.getFloat(R.styleable.RecyclerViewBanner_touchWaitTime, 30 * 1000);
        }finally {
            typedArray.recycle();
        }
        pointAttr = new PointAttr();
        pointAttr.setPointMargin(pointMargin);
        pointAttr.setPointMaxSize(pointMaxSize);
        pointAttr.setPointSelectedColor(pointSelectedColor);
        pointAttr.setPointUnSelectedColor(pointUnSelectedColor);
        pointAttr.setPointSize(pointSize);
    }

    public boolean isVisiable() {
        return isVisiable;
    }

    public void setVisiable(boolean visiable) {
        isVisiable = visiable;
    }

    /*
        * 检查当前是触摸状态、recycleview自己滑动状态
        * */
    private void checkTouchState() {
        if (isCheckTime) {
            return;
        }
        if (timer != null || timerTask != null) {
            return;
        }
        isCheckTime = true;

        timer = new Timer();
        timerTask = new TimerTask() {
            @Override
            public void run() {
                if (System.currentTimeMillis() - lastTouchTime >= touchWaitTime && !isPlaying) {
                    isTouched = false;
                    if (onTouchListenner != null) {
                        onTouchListenner.onTouched(isTouched);
                    }
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            Log.d(TAG, "Runnable");
                            setPlaying(true);
                            isCheckTime = false;
                            stopTimerTask();
                        }
                    });
                }

            }
        };
        timer.schedule(timerTask, 0, 1000);
    }

    private void stopTimerTask() {
        if (timer != null) {
            timer = null;
        }
        if (timerTask != null) {
            timerTask.cancel();
            timerTask = null;
        }
    }

    /**
     * 设置轮播间隔时间
     *
     * @param millisecond 时间毫秒
     */
    public void setIndicatorInterval(int millisecond) {
        this.mInterval = millisecond;
    }

    /**
     * 设置是否自动播放（上锁）
     *
     * @param playing 开始播放
     */
    private synchronized void setPlaying(boolean playing) {
        if (isAutoPlaying) {
            if (!isPlaying && playing && adapter != null && adapter.getItemCount() >= 2) {
                handler.postDelayed(playTask, mInterval);
                isPlaying = true;
            } else if (isPlaying && !playing) {
                handler.removeCallbacksAndMessages(null);
                isPlaying = false;
            }
        }
    }

    /**
     * 设置是否禁止滚动播放
     *
     * @param isAutoPlaying true  是自动滚动播放,false 是禁止自动滚动
     */
    public void setRvAutoPlaying(boolean isAutoPlaying) {
        this.isAutoPlaying = isAutoPlaying;
    }

    /**
     * 设置轮播数据集
     *
     * @param data Banner对象列表
     */
    public void setRvBannerData(List<Coffee> data) {
        setPlaying(false);
        mData.clear();
        if (data != null) {
            mData.addAll(data);
        }
        if (mData.size() > 1) {
            if (createCoffeeLayoutHelper != null) {
                createCoffeeLayoutHelper.init(mData);
                pageCount = createCoffeeLayoutHelper.getPageCount();
            }
            pointAttr.setPointNum(pageCount);
            currentIndex = mData.size() * 100;
            createPointHelper.setCurSelectedIndex(currentIndex % pageCount);
            createPointHelper.create(pointAttr);

            adapter.notifyDataSetChanged();
            mRecyclerView.scrollToPosition(currentIndex);
            setPlaying(true);
        } else {
            currentIndex = 0;
            adapter.notifyDataSetChanged();
        }
    }

    public void setOnChildClickListenner(OnCoffeeChildClickListenner onChildClickListenner) {

        this.onChildClickListenner = onChildClickListenner;
    }

    public void showNext() {

        if (pageCount <= 1) {
            return;
        }
        isTouched = true;
        lastTouchTime = System.currentTimeMillis();
        if (isPlaying) {
            setPlaying(false);
        }
        mRecyclerView.smoothScrollToPosition(++currentIndex);
        createPointHelper.changeSelectedPoint(currentIndex);
        if (!isCheckTime) {
            checkTouchState();
        }
    }

    public void showPrevious() {

        if (pageCount <= 1) {
            return;
        }

        if (isPlaying) {
            setPlaying(false);
        }
        lastTouchTime = System.currentTimeMillis();
        isTouched = true;

        currentIndex = (currentIndex - 1) < 0 ? currentIndex + pageCount - 1 : (currentIndex - 1);
        Log.d(TAG, "currentIndex = " + currentIndex);
        mRecyclerView.smoothScrollToPosition(currentIndex);
        createPointHelper.changeSelectedPoint(currentIndex);
        if (!isCheckTime) {
            checkTouchState();
        }
    }

    public void setOnTouchListenner(OnRecycleTouchListenner onTouchListenner) {
        this.onTouchListenner = onTouchListenner;
    }

    public void setIsPlay(boolean isPlay) {
        setPlaying(isPlay);
    }

    boolean isParentMoved = false;

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        //手动触摸的时候，停止自动播放，根据手势变换
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                startX = (int) ev.getX();
                startY = (int) ev.getY();
                // getParent().requestDisallowInterceptTouchEvent(true);
                setPlaying(false);//按下便不能滑动

                if (onTouchListenner != null) {
                    onTouchListenner.onTouched(true);
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX = (int) ev.getX();
                int moveY = (int) ev.getY();
                int disX = moveX - startX;
                int disY = moveY - startY;
                Log.d(TAG, "disX= " + disX);
                boolean hasMoved = Math.abs(disX) > Math.abs(disY) && Math.abs(disX) > 30;
                if (hasMoved && isPlaying) {
                    //  setPlaying(false);
                }
                if (hasMoved && !isParentMoved) {
                    isParentMoved = true;
                }
                break;
            case MotionEvent.ACTION_UP:
                Log.d(TAG, "ACTION_UP");
                isParentMoved = false;

                if (!isPlaying) {
                    isTouched = true;

                    lastTouchTime = System.currentTimeMillis();
                    if (!isCheckTime) {
                        checkTouchState();
                    }
                }
                break;


            case MotionEvent.ACTION_CANCEL:
                Log.d(TAG, "ACTION_CANCEL");
                if (!isPlaying) {
                    isTouched = true;

                    lastTouchTime = System.currentTimeMillis();
                    if (!isCheckTime) {
                        checkTouchState();
                    }
                }
                isParentMoved = false;
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        setPlaying(true);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        setPlaying(false);
    }

    @Override
    protected void onWindowVisibilityChanged(int visibility) {
        if (visibility == GONE || visibility == INVISIBLE) {
            // 停止轮播
            setPlaying(false);
        } else if (visibility == VISIBLE) {
            // 开始轮播
            setPlaying(true);
        }
        super.onWindowVisibilityChanged(visibility);
    }

    boolean isStartScale = false;
    View curTouchView = null;
    int downX = 0;
    int downY = 0;

    private class RecyclerAdapter extends RecyclerView.Adapter {

        @Override
        public BannerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            Log.d(TAG, "onCreateViewHolder");
            LinearLayout linearLayout = new LinearLayout(context);
            LinearLayout.LayoutParams linearLayoutParams = new LinearLayout.LayoutParams(
                    RecyclerView.LayoutParams.MATCH_PARENT,
                    RecyclerView.LayoutParams.MATCH_PARENT);//这里如果用WRAP_CONTENT，会出现一弹一弹的效果
            linearLayoutParams.gravity = Gravity.CENTER;
            linearLayout.setOrientation(LinearLayout.HORIZONTAL);
            linearLayout.setLayoutParams(linearLayoutParams);
            linearLayout.setId(Integer.MAX_VALUE - 1);
            /*return new RecyclerView.ViewHolder(linearLayout) {
            };*/
            for (int i = 0; i < CreateCoffeeLayoutHelper.OnePageCoffeeNum; i++) {

                View view = createCoffeeLayoutHelper.getView(context);
                linearLayout.addView(view);
            }

//            return new RecyclerView.ViewHolder(linearLayout) {};
            return new BannerViewHolder(linearLayout);
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            curPosition = position;

            BannerViewHolder myHolder = (BannerViewHolder) holder;
            final LinearLayout layout = (LinearLayout) holder.itemView;

            final List<Coffee> coffeeList = createCoffeeLayoutHelper.getOnePageCoffees(position, mData);
            if (coffeeList != null && coffeeList.size() > 0) {
                myHolder.bindView(coffeeList, position);
            }
       /*     final LinearLayout layout = (LinearLayout) holder.itemView;
            layout.removeAllViews();//如果不执行这句代码，会导致数据错乱显示
            final List<Coffee> coffeeList = createCoffeeLayoutHelper.getOnePageCoffees(position, mData);
            for (int i = 0; i < coffeeList.size(); i++) {
                final int index = i;
                final View view = createCoffeeLayoutHelper.getView(context, coffeeList, i);
                view.setTag(i);

                view.setOnTouchListener(new OnTouchListener() {
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        curTouchView = view;
                        switch (event.getAction()) {

                            case MotionEvent.ACTION_DOWN:
                                MyLog.d(TAG, "---------ACTION_DOWN");
                                if (System.currentTimeMillis() - lastClickTime < 2 * 1000) {
                                    isStartScale = false;
                                    break;
                                }
                                if (isStartScale) {
                                    break;
                                }
                                //如果已经售罄
                                if (coffeeList.get(index).isOver()) {

                                    isStartScale = false;
                                    coffeeScaleAnim(view, 1f, TradeAnimManager.IMAGE_SCALE, coffeeList.get(index).isOver());

                                    break;
                                } else {

                                    isStartScale = true;
                                    lastClickTime = System.currentTimeMillis();
                                    downX = (int) event.getX();
                                    downY = (int) event.getY();
                                    if (onChildClickListenner != null && !coffeeList.get(index).isOver()) {
                                        ChooseCoffeeInfo coffeeInfo = setChooseCoffeeInfo(view, coffeeList.get(index));
                                        if (coffeeInfo.isVilid()) {
                                            onChildClickListenner.onClick(coffeeInfo);
                                        }
                                    }
                                    //执行缩放动画，并将结果
                                    view.clearAnimation();

                                    coffeeScaleAnim(view, 1f, TradeAnimManager.IMAGE_SCALE, coffeeList.get(index).isOver());

                                    break;
                                }


                            case MotionEvent.ACTION_MOVE:

                                int moveX = (int) Math.abs(event.getX() - downX);
                                int moveY = (int) Math.abs(event.getY() - downY);

                                Log.d(TAG, "---------moveX=" + moveX);
                                Log.d(TAG, "---------moveY=" + moveY);
                                Log.d(TAG, "---------isParentMoved=" + isParentMoved);
                                Log.d(TAG, "---------ACTION_MOVE");
                                if (isStartScale) {

                                    if (moveX > 20 || moveY > 100 || isParentMoved) {
                                        isStartScale = false;
                                        coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffeeList.get(index).isOver());
                                    }

                                }

                                break;

                            case MotionEvent.ACTION_UP:
                                Log.d(TAG, "---------ACTION_MOVE");

                                if (isStartScale) {
                                    if (System.currentTimeMillis() - lastClickTime >= 5 * 1000) {//如果按下大于5s

                                        isStartScale = false;
                                        coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffeeList.get(index).isOver());
                                    } else {
                                        viewTouchEnd(true, lastClickTime, coffeeList.get(index).isOver());
                                        handler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                isStartScale = false;
                                                coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffeeList.get(index).isOver());
                                            }
                                        }, 1000);
                                    }
                                }
                                break;
                            case MotionEvent.ACTION_CANCEL:
                                if (isStartScale) {

                                    isStartScale = false;
                                    coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffeeList.get(index).isOver());
                                }
                                Log.d(TAG, " --------------ACTION_CANCEL");
                                break;
                        }
                        return true;
                    }
                });
               *//* view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (System.currentTimeMillis() - lastClickTime < 2 * 1000) {

                            return;
                        }
                        lastClickTime = System.currentTimeMillis();
                        if (onChildClickListenner != null && !coffeeList.get(index).isOver()) {
                            ChooseCoffeeInfo coffeeInfo = setChooseCoffeeInfo(view, coffeeList.get(index));
                            if (coffeeInfo.isVilid()) {
                                onChildClickListenner.onClick(coffeeInfo);
                            }
                        }
                        //执行缩放动画，并将结果
                        view.clearAnimation();
                        scaleAnim(view, 1f, TradeAnimManager.IMAGE_SCALE - 0.2f, coffeeList.get(index).isOver());
                    }
                });
*//*
                layout.addView(view);
            }*/
        }

        @Override

        public int getItemCount() {

            Log.d(TAG, "getItemCount =" + pageCount);
            return pageCount == 0 ? 0 : pageCount < 2 ? pageCount : Integer.MAX_VALUE;
        }
    }

    /*
    * 按下时，咖啡缩小
    * */
    private void coffeeScaleAnim(final View view, final float from, final float to, final boolean isOver) {
        ObjectAnimator objectAnimator = ObjectAnimatorUtil.scaleAnimator(view, "X", from, to);
        ObjectAnimator objectAnimator1 = ObjectAnimatorUtil.scaleAnimator(view, "Y", from, to);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(objectAnimator).with(objectAnimator1);
        animatorSet.setDuration(250);

        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                if (isOver && from > to) {
                    coffeeScaleAnim(view, to, from, isOver);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.start();
    }


    private void viewTouchEnd(boolean b, long lastClickTime, final boolean over) {

        if (b) {//如果手指松开
            if (System.currentTimeMillis() - lastClickTime > 200) {//如果距离触摸大于200ms
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (onChildClickListenner != null && !over) {

                            isTouched = false;//关闭线程

                            onChildClickListenner.onAnimEnd();
                        }
                    }
                });
            } else {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (onChildClickListenner != null && !over) {

                            isTouched = false;//关闭线程

                            onChildClickListenner.onAnimEnd();
                        }
                    }
                }, 200 - (System.currentTimeMillis() - lastClickTime));
            }

        } else {//如果手指未松开
        }
    }

    private ChooseCoffeeInfo setChooseCoffeeInfo(View view, Coffee coffee) {


        ChooseCoffeeInfo coffeeInfo = new ChooseCoffeeInfo();

/*        Bitmap imageCache = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(imageCache);
        view.draw(canvas);*/
        CoffeeRoundImage image = (CoffeeRoundImage) view.findViewById(R.id.coffeeImg);
        final int location[] = new int[2];
        image.getLocationOnScreen(location);
//        ChooseCoffeeInfo.getInstance().setCacheImage(imageCache);
        if (coffee.getImageBitmap() != null) {//view.getTag()
            coffeeInfo.setCropImage(coffee.getImageBitmap());
        } else {
            Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.mipmap.no_coffee);
            coffeeInfo.setCropImage(bitmap);
        }
        coffeeInfo.setCoffee(coffee);
        coffeeInfo.setLocationX(location[0] + image.getWidth() / 2);
        coffeeInfo.setLocationY(location[1] + image.getHeight() / 2);
        coffeeInfo.setMinWidth((int) (image.getWidth() * TradeAnimManager.IMAGE_SCALE));//* TradeAnimManager.IMAGE_SCALE
        coffeeInfo.setMinHeight((int) (image.getHeight() * TradeAnimManager.IMAGE_SCALE));//* TradeAnimManager.IMAGE_SCALE
        coffeeInfo.setBuyState(BuyState.ALIPAY_WECHAT_BUY);
        return coffeeInfo;
    }

    /*
    * item点击时的缩放效果
    * */
    private void scaleAnim(final View view, final float from, final float to, final boolean isOver) {


        ObjectAnimator objectAnimator = ObjectAnimatorUtil.scaleAnimator(view, "X", from, to);
        ObjectAnimator objectAnimator1 = ObjectAnimatorUtil.scaleAnimator(view, "Y", from, to);

        AnimatorSet animatorSet = new AnimatorSet();
        animatorSet.play(objectAnimator).with(objectAnimator1);
        animatorSet.setDuration(250);
       /* if (from < to) {
            animatorSet.setStartDelay(200);
        }*/
        animatorSet.addListener(new Animator.AnimatorListener() {
            @Override
            public void onAnimationStart(Animator animation) {
                if (from > to) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            if (onChildClickListenner != null && !isOver) {

                                isTouched = false;//关闭线程

                                onChildClickListenner.onAnimEnd();
                            }
                        }
                    }, 200);

                }
            }

            @Override
            public void onAnimationEnd(Animator animation) {

                view.clearAnimation();

                if (from > to) {//缩小

                    scaleAnim(view, to, from, isOver);
                } else { //放大
                    view.clearAnimation();
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }
        });
        animatorSet.start();
    }


   /* private class MyPagerSnapHelper extends LinearSnapHelper {

        @Override
        public int findTargetSnapPosition(RecyclerView.LayoutManager layoutManager, int velocityX, int velocityY) {
            int targetPos = super.findTargetSnapPosition(layoutManager, velocityX, velocityY);
            final View currentView = findSnapView(layoutManager);
            if (targetPos != RecyclerView.NO_POSITION && currentView != null) {
                int currentPos = layoutManager.getPosition(currentView);
                int first = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();
                int last = ((LinearLayoutManager) layoutManager).findLastVisibleItemPosition();
                currentPos = targetPos < currentPos ? last : (targetPos > currentPos ? first : currentPos);
                targetPos = targetPos < currentPos ? currentPos - 1 : (targetPos > currentPos ? currentPos + 1 : currentPos);
            }
            return targetPos;
        }
    }*/

    private class FastScrollLinearLayoutManager extends LinearLayoutManager {

        public FastScrollLinearLayoutManager(Context context) {
            super(context);
        }

        public FastScrollLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }

        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
            LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {

                @Override
                public PointF computeScrollVectorForPosition(int targetPosition) {
                    return FastScrollLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
                }

                //该方法控制速度。
                //if returned value is 2 ms, it means scrolling 1000 pixels with LinearInterpolation should take 2 seconds.
                @Override
                protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                /*
                     控制单位速度,  毫秒/像素, 滑动1像素需要多少毫秒.

                     默认为 (25F/densityDpi) 毫秒/像素

                     mdpi上, 1英寸有160个像素点, 25/160,
                     xxhdpi,1英寸有480个像素点, 25/480,
                  */

//                    return 10F / displayMetrics.densityDpi;//可以减少时间，默认25F
                    return super.calculateSpeedPerPixel(displayMetrics);
                }

                //该方法计算滑动所需时间。在此处间接控制速度。
                //Calculates the time it should take to scroll the given distance (in pixels)
                @Override
                protected int calculateTimeForScrolling(int dx) {
               /*
                   控制距离, 然后根据上面那个方(calculateSpeedPerPixel())提供的速度算出时间,

                   默认一次 滚动 TARGET_SEEK_SCROLL_DISTANCE_PX = 10000个像素,

                   在此处可以减少该值来达到减少滚动时间的目的.
                */

                    //间接计算时提高速度，也可以直接在calculateSpeedPerPixel提高

                    Log.d(TAG, "dx= " + dx);
                    if (dx > 3000) {
                        dx = 3000;
                    }

                    int time = super.calculateTimeForScrolling(dx);
                    Log.d(TAG, "calculateTimeForScrolling = " + time);

                    time = 500;

                    return time;
                }
            };

            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }
    }

    class BannerViewHolder extends RecyclerView.ViewHolder {

        LinearLayout layout;

        public BannerViewHolder(View itemView) {
            super(itemView);
            layout = (LinearLayout) itemView;
        }

        public void bindView(List<Coffee> coffees, int position) {
            int startIndex = createCoffeeLayoutHelper.getStartIndex(position);

            for (int i = 0; i < layout.getChildCount(); i++) {
                View view = layout.getChildAt(i);
                if (i >= coffees.size()) {
                    view.setVisibility(GONE);
                } else {
                    Coffee coffee = coffees.get(i);
                    createCoffeeLayoutHelper.bindDatas(context, view, coffee);
                    view.setVisibility(VISIBLE);
                    bindListenner(view, startIndex + i, coffee);
                }
            }
        }

        private void bindListenner(final View view, int index, final Coffee coffee) {
            view.setTag(index);

            view.setOnTouchListener(new OnTouchListener() {
                @Override
                public boolean onTouch(View v, MotionEvent event) {

                    switch (event.getAction()) {

                        case MotionEvent.ACTION_DOWN:
                            MyLog.d(TAG, "---------ACTION_DOWN");
                            if (System.currentTimeMillis() - lastClickTime < 2 * 1000) {
                                isStartScale = false;
                                break;
                            }
                            if (isStartScale) {
                                break;
                            }
                            //如果已经售罄
                            if (coffee.isOver()) {

                                isStartScale = false;
                                coffeeScaleAnim(view, 1f, TradeAnimManager.IMAGE_SCALE, coffee.isOver());

                                break;
                            } else {

                                isStartScale = true;
                                lastClickTime = System.currentTimeMillis();
                                downX = (int) event.getX();
                                downY = (int) event.getY();
                                if (onChildClickListenner != null && !coffee.isOver()) {
                                    ChooseCoffeeInfo coffeeInfo = setChooseCoffeeInfo(view, coffee);
                                    if (coffeeInfo.isVilid()) {
                                        onChildClickListenner.onClick(coffeeInfo);
                                    }
                                }
                                //执行缩放动画，并将结果
                                view.clearAnimation();

                                coffeeScaleAnim(view, 1f, TradeAnimManager.IMAGE_SCALE, coffee.isOver());

                                break;
                            }


                        case MotionEvent.ACTION_MOVE:

                            int moveX = (int) Math.abs(event.getX() - downX);
                            int moveY = (int) Math.abs(event.getY() - downY);

                            Log.d(TAG, "---------moveX=" + moveX);
                            Log.d(TAG, "---------moveY=" + moveY);
                            Log.d(TAG, "---------isParentMoved=" + isParentMoved);
                            Log.d(TAG, "---------ACTION_MOVE");
                            if (isStartScale) {

                                if (moveX > 20 || moveY > 100 || isParentMoved) {
                                    isStartScale = false;
                                    coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffee.isOver());
                                }

                            }

                            break;

                        case MotionEvent.ACTION_UP:
                            Log.d(TAG, "---------ACTION_MOVE");

                            if (isStartScale) {
                                if (System.currentTimeMillis() - lastClickTime >= 5 * 1000) {//如果按下大于5s

                                    isStartScale = false;
                                    coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffee.isOver());
                                } else {
                                    viewTouchEnd(true, lastClickTime, coffee.isOver());
                                    handler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            isStartScale = false;
                                            coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffee.isOver());
                                        }
                                    }, 1000);
                                }
                            }
                            break;
                        case MotionEvent.ACTION_CANCEL:
                            if (isStartScale) {

                                isStartScale = false;
                                coffeeScaleAnim(view, TradeAnimManager.IMAGE_SCALE, 1f, coffee.isOver());
                            }
                            Log.d(TAG, " --------------ACTION_CANCEL");
                            break;
                    }
                    return true;
                }
            });
        }


    }


}